import React, { forwardRef, useImperativeHandle, useState } from 'react'
import {
 Button, Form, Input, message, Modal,
} from 'antd'
import { connect } from '@umijs/max'
import styles from './index.less'

const { TextArea } = Input

const AuthModal = (props) => {
  const [modalVisible, setModalVisible] = useState(false)
  const [testLoading, setTestLoading] = useState(false)
  const [desc, setDesc] = useState({})
  const [form] = Form.useForm()

  useImperativeHandle(props.refInstance, () => ({
    toggleModal,
  }))

  const toggleModal = (data) => {
    if (!modalVisible) {
      form.resetFields()
      setDesc(data)
    }

    setModalVisible(!modalVisible)
  }

  const handleApprove = (approveOrder) => {
    form.validateFields().then(values => {
      setTestLoading(true)
      const { id } = desc || {}
      const { approveReason } = values
      props.dispatch({
        type: 'authApproval/queryApproveUserApiAuthById',
        params: {
          approveOrder,
          id,
          approveReason,
        },
        cb: (res) => {
          const { msg, status } = res
          setTestLoading(false)
          if (status === 200) {
            message.success('操作成功')
            toggleModal()
            props?.forceUpdateFn()
          } else {
            message.error(msg || '服务端错误')
          }
        },
      })
    })
  }

  return (
    <Modal
      title="授权审批"
      visible={modalVisible}
      maskClosable={false}
      // forceRender={false}
      width={520}
      footer={[
        <Button danger loading={testLoading} type="primary" key={1} onClick={() => { handleApprove(0) }}>拒绝</Button>,
        <Button key={2} loading={testLoading} onClick={() => { handleApprove(1) }} type="primary">通过</Button>,
      ]}
      onCancel={toggleModal}
    >
      <Form
        form={form}
        className={styles.form}
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <Form.Item
          label="API名称"
          name="ApiName"
          initialValue={desc?.apiName}
        >
          <Input disabled placeholder="请输入中文名称" />
        </Form.Item>
        <Form.Item
          label="申请人"
          name="userName"
          initialValue={desc?.userName}
        >
          <Input disabled placeholder="请输入申请人" />
        </Form.Item>
        <Form.Item
          label="审批说明"
          name="approveReason"
        >
          <TextArea rows={4} placeholder="请输入审批说明" />
        </Form.Item>
      </Form>
    </Modal>
  )
}

const IComponent = connect(({ authApproval }) => ({ ...authApproval }))(AuthModal)

export default forwardRef((props, ref) => <IComponent {...props} refInstance={ref} />)
